/*
 * @Author: your name
 * @Date: 2021-08-03 17:06:33
 * @LastEditTime: 2021-08-06 21:39:39
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hrsaas-86\src\store\modules\user.js
 */
/*
 * @Author: your name
 * @Date: 2021-08-03 17:06:33
 * @LastEditTime: 2021-08-04 21:02:16
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hrsaas-86\src\store\modules\user.js
 */
//  用户模块的store, 后期自己实现 , 这里面的代码有参考价值 后期在写这个模块的时候
//  打开源码对比梳理
import { reqLogin, reqGetUserInfo, reqGetUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  // 设置个人信息的mutation
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  },
  // 清除token
  removeToken(state) {
    state.token = null // 清除vuex中
    removeToken() // 清除本地
  }
}
const actions = {
  async login({ commit }, userInfo) {
    // 发送请求,
    const res = await reqLogin(userInfo)
    // 再去提交存储个人信息的mutation
    commit('setToken', res.data)
    return res
  },
  logout({ commit }) {
    commit('removeUserInfo')
    commit('removeToken')
  },
  // 获取个人信息的action
  async getUserInfo({ commit }) {
    const { data } = await reqGetUserInfo()
    const { data: data2 } = await reqGetUserDetailById(data.userId)
    const result = { ...data, ...data2 }
    commit('setUserInfo', result)
    return result
  }
}
export default {
  // 开启命名空间
  namespaced: true,
  state,
  mutations,
  actions
}
